'use strict';

//云函数：关键词搜索日常账单
const db = uniCloud.database();
const collection = db.collection('money');
const dbCmd = db.command;

exports.main = async (event, context) => {
	//event为客户端上传的参数
	let res = null;

	if (!event.pageNumber || !event.pageSize || !event.userId) {
		return {
			code: 0,
			msg: '请检查传参！'
		};
	}

	let matchOrder = null;

	// 按照时间查询
	if (event.date) {
		matchOrder = dbCmd.or([{
			userId: event.userId,
			date: new RegExp('.*' + event.date + '.*')
		}])

	// 按照关键词查询（备注，类型，时间）
	} else if (event.value) {
		matchOrder = dbCmd.or([{
				userId: event.userId,
				remarks: new RegExp('.*' + event.value + '.*')
			},
			{
				userId: event.userId,
				type: new RegExp('.*' + event.value + '.*')
			},
			{
				userId: event.userId,
				date: new RegExp('.*' + event.value + '.*')
			}
		])
		
	// 当前用户所有账单
	} else {
		matchOrder = {
			userId: event.userId
		}
	}

	res = await collection.aggregate().match(matchOrder).sort({
		date: -1
	}).skip((event.pageNumber - 1) * event.pageSize).limit(event.pageSize).end();




	//返回数据给客户端
	if (res) {
		return {
			code: 1,
			msg: '查询成功',
			data: res
		};
	} else {
		return {
			code: 0,
			msg: '查询失败'
		};
	}
};
